<template>
  <div class="mainsu">
    <div class="main_spac1">
      <div class="main_white padding10 paddingBottom20">
        <el-form
          :inline="true"
          :rules="rules"
          :model="monitorForm"
          class="demo-form-inline"
          ref="userListFrom"
          label-width="90px"
        >
          <div class="main_crumbs boxdq">
            <div class="main_crumbs_l">
              <a href="javascript:;" @click="$router.back(-1)">
                <i class="el-icon-arrow-down"></i>返回
              </a>
              <em>|</em>
              <span>快捷盘点</span>
            </div>
          </div>
          <div class="marginTop15">
            <div class="mainor_form">
              <el-form-item
                label="商品分类："
                prop="form.category_id"
                class="wid220"
              >
                <el-cascader
                  v-model="monitorForm.form.category_id"
                  :options="options"
                  :props="defaultProps"
                ></el-cascader>
              </el-form-item>

              <el-form-item label="库存情况：" prop="form.inventory_type">
                <el-select
                  v-model.trim="monitorForm.form.inventory_type"
                  placeholder="库存情况"
                  class="wid220"
                >
                  <el-option label="所有" value=""></el-option>
                  <el-option
                    v-for="(inventory, index) in info.inventory"
                    :key="index"
                    :label="inventory"
                    :value="parseInt(index)"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="标品：" prop="form.is_standard">
                <el-select
                  v-model.trim="monitorForm.form.is_standard"
                  placeholder="是否标品"
                  class="wid220"
                >
                  <el-option label="所有" value=""></el-option>
                  <el-option
                    v-for="(is_standard_list,
                    index) in info.is_standard_list"
                    :key="index"
                    :label="is_standard_list"
                    :value="parseInt(index + 1)"
                  ></el-option>
                </el-select>
              </el-form-item>
              <MainFormBtn @reset="reset" @getSearchFor="getArticleList" :loading="listLoading" :showBtn="moredata" />
              <div class="more el-form-item" @click="more">
                <span>更多</span>
                <i :class="[{ on: moredata }, ' el-icon-arrow-down']"></i>
              </div>
              <div class="clearfix"></div>
              <el-collapse-transition>
                <div v-show="moredata" style="width: 100%">
                  <el-form-item label="商品：" prop="form.goods_spu_id">
                    <change-goods-input
                      isInventory
                      ref="changeGoodsInput"
                      @clear="
                        () => {
                          this.form.goods_spu_id = '';
                        }
                      "
                      @sendValue="
                        data => {
                          this.monitorForm.form.goods_spu_id = data.id;
                        }
                      "
                    ></change-goods-input>
                  </el-form-item>
                  <div class="clearfix"></div>
                  <el-form-item label=" ">
                    <MainFormBtn class="btn-bottom" @reset="reset" @getSearchFor="getArticleList" :loading="listLoading" :showBtn="!moredata" />
                  </el-form-item>
                </div>
              </el-collapse-transition>
            </div>
            <div class="main-controls-wrap">
              <div>
                <el-button @click="bulkFillZero">批量填充0</el-button>
                <el-button :disabled="bulkConfirm_disabled" @click="bulkConfirm">批量确认</el-button>
              </div>
            </div>
            <div class="main_table marginTop10">
              <el-table
                ref="multipleTable"
                v-loading="listLoading"
                :data="monitorForm.list.data"
                element-loading-text="加载中"
                fit
                border
                key="multipleTable"
                highlight-current-row
                :header-cell-class-name="this.$verticaline"
              >
                <el-table-column width="50">
                  <template #header>
                    <el-checkbox
                      @change="val => changeAll(val)"
                      v-model="checkAll"
                    ></el-checkbox>
                  </template>
                  <template slot-scope="scope">
                    <el-checkbox
                      @change="val => oneChange(val, scope.row)"
                      v-model="scope.row.checked"
                    ></el-checkbox>
                  </template>
                </el-table-column>
                <el-table-column label="商品名称" prop="name">
                  <template slot-scope="scope"
                    >{{ scope.row.goods.name }}【{{
                      scope.row.goods_spu.spu_name
                        ? scope.row.goods_spu.spu_name.title
                        : "s"
                    }}】</template
                  >
                </el-table-column>
                <el-table-column label="单位" prop="goods_spu.spu_unit.title" />
                <el-table-column label="系统库存" prop="num" />
                <el-table-column
                  label="实际库存"
                  prop="inventory_num"
                  class-name="main_hei"
                >
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'list.data.' + scope.$index + '.inventory_num'"
                      :rules="rules.inventory_num"
                      label-width="10px"
                      label=" "
                    >
                      <el-input
                        :ref="'inventory_num' + scope.$index"
                        v-model.trim="scope.row.inventory_num"
                        :class="['inventory_num_' + scope.$index]"
                        placeholder="实际库存"
                        class="wid110"
                        @change="isEdit = true"
                        @keyup.enter.native="changeNum(scope, $event, 1)"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="备注"
                  prop="remark"
                  width="350"
                  class-name="main_hei"
                >
                  <template slot-scope="scope">
                    <el-form-item label-width="0" label="">
                      <el-input
                        v-model.trim="scope.row.remark"
                        placeholder="备注"
                        class="wid240"
                        @change="isEdit = true"
                        @keyup.enter.native="changeNum(scope, $event, 2)"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="管理操作"
                  align="center"
                  fixed="right"
                  width="140"
                  class-name="main_hei"
                >
                  <template slot-scope="scope">
                    <el-link
                      type="success"
                      @click="confirm(scope.$index, scope.row)"
                      >确认</el-link
                    >
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="main_page boxdq">
              <div></div>
              <!-- 分页 -->
              <div class="main_page_r">
                <MainPagination
                  :current-page="current.page"
                  :page-sizes="[20, 30, 50, 100]"
                  :page-size="limit"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="totalCount"
                  background
                  @size-change="changeLimit"
                  @current-change="changePage"
                />
              </div>
            </div>
          </div>
          <div class="main_tile boxdq marginTop20">
            <div class="main_tile_l marginLeft0"><em></em>商品信息</div>
          </div>
          <div class="main_xq marginTop10">
            <ul class="boxha">
              <li class="main_w100 box">
                备注：
                <div class="box main_xqi" style="margin-top: -4px">
                  <el-input
                    v-model.trim="monitorForm.form_xs.remark"
                    placeholder="备注"
                    clearable
                    style="width: 100%"
                    @change="isEdit = true"
                  ></el-input>
                </div>
              </li>
            </ul>
          </div>
          <div class="main_table main_table_xs marginTop10">
            <el-table
              ref="multipleTable"
              v-loading="listLoading"
              :data="monitorForm.list_xs"
              element-loading-text="加载中"
              fit
              highlight-current-row
              key="multipleTable1"
            >
              <el-table-column label="序号" width="80">
                <template slot-scope="scope">{{ scope.$index + 1 }}</template>
              </el-table-column>
              <el-table-column
                label="商品名称"
                prop="operate.name"
                class-name="main_hei"
              >
                <template slot-scope="scope"
                  >{{ scope.row.goods.name }}【{{
                    scope.row.goods_spu.spu_name
                      ? scope.row.goods_spu.spu_name.title
                      : ""
                  }}】</template
                >
              </el-table-column>
              <el-table-column
                label="单位"
                prop="goods_spu.spu_unit.title"
                class-name="main_hei"
              />
              <el-table-column
                label="实际库存"
                prop="inventory_num"
                class-name="main_hei"
              />
              <el-table-column
                label="备注"
                prop="remark"
                class-name="main_hei"
              />
              <el-table-column
                label="管理操作"
                align="center"
                fixed="right"
                width="240"
                class-name="main_hei"
              >
                <template slot-scope="scope">
                  <el-link type="danger" @click="delet(scope.$index)"
                    >删除</el-link
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form>
        <div class="newConBox_p200 paddingBottom10" id="newConBox">
          <div class="newConBox_h32">
            <div
              :class="['mainor_pr boxdq newConBox ', { on: searchBarFixed }]"
            >
              <div class="mainor_prl">
                <el-button
                  type="primary"
                  @click="preservation"
                  :loading="btn_loading"
                  v-repeatClick
                  >保存</el-button
                >
                <el-button @click="$router.back(-1), (isEdit = false)"
                  >取消</el-button
                >
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  inventorySheet_getGoodsSpu,
  inventorySheet_add
} from "@/api/warehouse/warehouseCheck";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import rules from "@/rules/warehouse/warehouseCheck_quick";
import { recursion, category } from "@/utils/index";
import { parseTime, jsonStringifyBack } from "@/utils/index";
import data from "../global/print_order_copy/data";

export default {
  components: {},
  data() {
    return {
      // 验证
      rules,
      // 分页
      current: {
        page: 1,
        per_page: 20
      },
      limit: 20,
      totalCount: 1,
      moredata: false,
      // 列表数据
      monitorForm: {
        form: {
          is_standard: null,
          goods_spu_id: "",
          inventory_type: null,
          pid: "",
          category_id: []
        },
        form_xs: {
          remark: ""
        },
        list_xs: [],
        list: {
          data: []
        }
      },
      info: [],
      listLoading: false,
      // 分类
      options: [],
      defaultProps: {
        children: "selfNext",
        label: "title",
        value: "id",
        checkStrictly: true
      },
      bulkConfirm_disabled: true,
      // 监听滚动
      searchBarFixed: false,
      isEdit: false,
      btn_loading: false,
      // 多选
      checkAll: false
    };
  },
  watch: {
    "monitorForm.list.data": {
      handler(val) {
        let all_list = val;
        let length = val.length;
        let alllength = 0;
        let arr = [];
        all_list.map(e => {
          if (e.checked) {
            alllength += 1;
            arr.push(e);
          }
        });
        this.selectArr = arr;
        if (alllength > 0) {
          this.bulkConfirm_disabled = false;
        } else {
          this.bulkConfirm_disabled = true;
        }
        if (length == alllength) {
          this.checkAll = true;
        } else {
          this.checkAll = false;
        }
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    window.addEventListener("scroll", this.handleScroll);
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
  created() {
    // 列表
    this.inventorySheet_getGoodsSpu();
  },
  beforeRouteLeave(to, from, next) {
    if (this.isEdit) {
      setTimeout(() => {
        this.$confirm(
          "您已经有数据操作，离开页面系统不会保存您的操作，确定离开吗？",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        )
          .then(() => {
            // 正常跳转
            next();
          })
          .catch(() => {
            next(false);
          });
      }, 200);
    } else {
      next();
    }
  },
  methods: {
    more() {
      this.moredata = !this.moredata
    },
    // 监听滚动
    handleScroll() {
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      scrollTop + document.documentElement.clientHeight >
      document.getElementById("newConBox").offsetTop + 300
        ? (this.searchBarFixed = false)
        : (this.searchBarFixed = true);
    },
    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.inventorySheet_getGoodsSpu();
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.inventorySheet_getGoodsSpu();
    },
    changePage(page) {
      this.current.page = page;
      this.inventorySheet_getGoodsSpu();
    },
    // 删除
    delet(index) {
      this.isEdit = true;
      this.monitorForm.list.data.push(
        JSON.parse(JSON.stringify(this.monitorForm.list_xs[index]))
      );
      this.monitorForm.list_xs.splice(index, 1);
    },
    //重置
    reset() {
      this.$refs["userListFrom"].resetFields();
      if (this.$refs["changeGoodsInput"]) {
        this.$refs["changeGoodsInput"].name = "";
      }
      this.createTime = [];
      this.sendTime = [];
      this.inventorySheet_getGoodsSpu();
    },
    // 确认
    confirm(index, row) {
      this.isEdit = true;
      if (parseFloat(this.monitorForm.list.data[index].inventory_num) >= 0) {
        let ind = 0;
        if (this.monitorForm.list_xs.length != 0) {
          let title = row.goods_spu.spu_name
            ? row.goods_spu.spu_name.title
            : "";
          let name = row.goods.name + "【" + title + "】";
          this.monitorForm.list_xs.map(e => {
            if (e.goods_spu_id == row.goods_spu_id) {
              ind = e.goods_spu_id;
              return;
            }
          });
          if (ind == 0) {
            this.monitorForm.list_xs.push(
              JSON.parse(JSON.stringify(this.monitorForm.list.data[index]))
            );
            this.monitorForm.list.data.splice(index, 1);
          } else {
            this.$confirm(`${name}商品已盘点，确认替换吗？`, {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            })
              .then(() => {
                this.monitorForm.list.data.splice(index, 1);
                this.monitorForm.list_xs.map(e => {
                  if (e.goods_spu_id == ind) {
                    e.inventory_num = row.inventory_num;
                  }
                });
                ind = 0;
              })
              .catch(() => {});
          }
        } else {
          this.monitorForm.list_xs.push(
            JSON.parse(JSON.stringify(this.monitorForm.list.data[index]))
          );
          this.monitorForm.list.data.splice(index, 1);
        }
      } else {
        this.$message.error("实际库存不能为空，可以为0或者数字");
      }
    },
    // 保存
    preservation() {
      this.$refs["userListFrom"].validate(valid => {
        if (valid) {
          if (this.monitorForm.list_xs.length == 0) {
            this.$message.error("请至少添加一个商品");
            return;
          }
          this.isEdit = false;
          this.btn_loading = true;
          let data = Object.assign(
            {
              sign: Md5(
                objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
              )
            },
            apiUrl().name,
            this.order_data().form,
            { list: JSON.stringify(this.order_data().arry, jsonStringifyBack) }
          );
          inventorySheet_add(data).then(res => {
            this.btn_loading = false;
            if (res.errcode == 0) {
              this.$message({
                message: "添加成功",
                type: "success"
              });
              this.$router.go(-1);
            } else {
              this.$message.error(res.errmsg);
            }
          });
        }
      });
    },
    order_data() {
      let form = JSON.parse(
        JSON.stringify(this.monitorForm.form_xs, jsonStringifyBack)
      );
      let arry = [];
      let sz = JSON.parse(
        JSON.stringify(this.monitorForm.list_xs, jsonStringifyBack)
      );
      sz.map(e => {
        arry.push({
          goods_id: e.goods_id,
          goods_spu_id: e.goods_spu_id,
          num: e.inventory_num,
          remark: e.remark,
          price: e.price
        });
      });
      return { form, arry };
    },
    // 列表
    inventorySheet_getGoodsSpu() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, this.list_form(), this.current)
            ) + apiUrl().appsecret
          )
        },
        apiUrl().name,
        this.list_form(),
        this.current
      );
      inventorySheet_getGoodsSpu(data).then(res => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.options = recursion(res.data.categoryList, true);
          res.data.list.data.map(e => {
            if (e.num < 0) {
              e.inventory_num = 0;
            } else {
              e.inventory_num = "";
            }
          });
          res.data.list.data.map(e => {
            e.checked = false;
          });
          this.monitorForm.list = res.data.list;
          this.info = res.data;
          this.totalCount = res.data.list.total;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    list_form() {
      let form = JSON.parse(JSON.stringify(this.monitorForm.form));
      form.pid = form.category_id[0] ? form.category_id[0] : "";
      form.category_id = category(form.category_id);
      return form;
    },
    // 选择全部
    changeAll(val) {
      // 全选反选
      this.monitorForm.list.data.map(e => {
        // if (parseFloat(e.inventory_num).toString() != "NaN") {
        //   e.checked = !e.checked;
        // } else {
        //   e.checked = false;
        // }
        e.checked = val;
      });
    },
    // 一级选择
    oneChange(val, row) {
      row.checked = val;
      // if (parseFloat(row.inventory_num).toString() != "NaN") {
      //   row.checked = val;
      // } else {
      //   row.checked = false;
      // }
    },
    // 批量填充0
    bulkFillZero() {
      this.monitorForm.list.data.map(e => {
        if (
          (e.inventory_num === "" ||
            e.inventory_num === null ||
            e.inventory_num === undefined) &&
          e.checked
        ) {
          e.inventory_num = 0;
        }
      });
    },
    // 批量确认
    bulkConfirm() {
      this.isEdit = true;
      let arr = JSON.parse(
        JSON.stringify(this.monitorForm.list_xs, jsonStringifyBack)
      );
      let selectArr = this.selectArr.filter(item => {
        if (item.checked && String(item.inventory_num)) {
          return item;
        }
      });
      let ind = 0;
      let all = 0;
      if (this.monitorForm.list_xs.length != 0) {
        selectArr.map(e => {
          this.monitorForm.list_xs.map(it => {
            if (e.goods_spu_id == it.goods_spu_id) {
              all += 1;
              ind = it.goods_spu_id;
              return;
            }
          });
        });
        if (ind == 0) {
          this.monitorForm.list_xs = arr.concat(selectArr);
        } else {
          this.$confirm(`${all}个商品重复盘点，确认替换吗？`, {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            title: "提示"
          })
            .then(() => {
              selectArr.map(a => {
                this.monitorForm.list_xs.map(f => {
                  if (a.goods_spu_id == f.goods_spu_id) {
                    f.inventory_num = a.inventory_num;
                  }
                });
              });
            })
            .catch(() => {});
        }
      } else {
        this.monitorForm.list_xs = arr.concat(selectArr);
      }
      let dataArr = this.monitorForm.list.data;
      let newarr = [];
      dataArr.map(e => {
        if (!selectArr.includes(e)) {
          newarr.push(e);
        }
      });
      this.monitorForm.list.data = newarr;
      this.selectArr = [];
    },
    // 实际库存  备注填写
    changeNum(scope, $event, type) {
      let remark = scope.row.remark;
      let index = scope.$index;
      let inventory_num = scope.row.inventory_num;
      switch (type) {
        case 1:
          if (
            /^(\d+\.?)?\d{0,4}$/.test(parseFloat(inventory_num)) &&
            inventory_num != ""
          ) {
            this.confirm(scope.$index);
          } else {
            this.$message.error("请输入数字");
          }
          break;
        case 2:
          if (
            /^(\d+\.?)?\d{0,4}$/.test(parseFloat(inventory_num)) &&
            inventory_num != ""
          ) {
            this.confirm(scope.$index);
          } else {
            this.$message.error("请输入实际库存");
            this.$nextTick(() => {
              let str = "inventory_num_" + scope.$index;
              let input = document
                .querySelector(`.${str}`)
                .querySelector("input");

              input.focus();
            });
          }
          break;
      }
    },
    inputBlur() {}
  }
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";
/deep/.main_table .el-table--small td {
  padding: 0;
}
.more.el-form-item {
  margin-bottom: 0;
}
.mainsu {
  /deep/.el-form-item--small.el-form-item {
    margin-bottom: 9px;
  }
  .mainor_form form {
    width: 100%;
  }
  .reset {
    background: none;
    color: #03a98e;
  }
  .main_table {
    /deep/.el-table--small td {
      padding-top: 0;
    }
    /deep/.el-form-item--small.el-form-item {
      margin-bottom: 16px;
      margin-top: 16px;
      margin-right: 0;
    }
  }
  .main_table_xs {
    /deep/.el-table--small td {
      padding-top: 12px;
    }
  }
  .main_xq {
    ul {
      li {
        .main_xqi {
          width: 80%;
          margin-left: 5px;
        }
      }
    }
  }
}
.marginTop15 {
  position: relative;
}
.mainor_te {
  position: absolute;
  top: 0;
  right: 0;
  z-index: 3;
}
</style>
